from flask import Flask, render_template, request, flash, redirect, url_for
import os
import threading
import queue
import time
import subprocess
import json
import predict
import base64

app = Flask(__name__)
app.secret_key = 'ligongzzz'


def get_base64_image(img_path: str):
    with open(img_path, "rb") as f:  # 转为二进制格式
        base64_data = base64.b64encode(f.read())  # 使用base64进行加密
        return str(base64_data, encoding="utf-8")


@app.route('/rssi', methods=['GET'])
def hello_world():
    json_to_return = {}
    try:
        data = request.args.get("test")
        # print(data)
        data_object = json.loads(data)
        name_id = data_object["ID"]
        rssi_map = data_object["RSSIMap"]
        
        # Preprocess Data
        process_result = predict.preprocess(rssi_map=rssi_map, name_id=name_id)
        if process_result == 1:
            json_to_return['result'] = 1
        else:
            answer = predict.predict(rssi_map, name_id=name_id)
            json_to_return['result'] = 0

    except Exception as err:
        print(err)
        json_to_return['result'] = -1
    return json.dumps(json_to_return), 200, {}


@app.route('/', methods=['GET', 'post'])
def tupian():
    base64_data = get_base64_image('result.png')
    fstr = f"""<img src="data:image/png;base64,{str(base64_data)}"/>"""
    # print(fstr)
    return fstr, 200, {}


app.run(debug=True, host='0.0.0.0', port=80)
